//
//  CommonWebviewController.m
//  DigitalCampus
//
//  Created by 刘占宇 on 16/5/14.
//  Copyright © 2016年 刘占宇. All rights reserved.
//

#import "CommonWebviewController.h"
#import "NJKWebViewProgressView.h"
#import "NJKWebViewProgress.h"
#import "MWPhotoBrowser.h"
@interface CommonWebviewController ()<UIWebViewDelegate, NJKWebViewProgressDelegate,MWPhotoBrowserDelegate>
{
    NJKWebViewProgressView *_progressView;
    NJKWebViewProgress *_progressProxy;
    MWPhoto *photo;
    NSMutableArray *photos;
    NSMutableArray *thumbs;
    BOOL displayActionButton;
    BOOL displaySelectionButtons;
    BOOL displayNavArrows;
    BOOL enableGrid;
    BOOL startOnGrid;
}
@property (weak, nonatomic) IBOutlet UIWebView *webView;
@property (strong, nonatomic) NSArray *imageArray;
@end

@implementation CommonWebviewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.webView.backgroundColor = [UIColor whiteColor];
    _progressProxy = [[NJKWebViewProgress alloc] init];
    _webView.delegate = _progressProxy;
    _progressProxy.webViewProxyDelegate = self;
    _progressProxy.progressDelegate = self;
    displayActionButton = YES;
    displaySelectionButtons = NO;
    displayNavArrows = YES;
    enableGrid = YES;
    startOnGrid = NO;
    CGFloat progressBarHeight = 2.0f;
    CGRect navigationBarBounds = self.navigationController.navigationBar.bounds;
    CGRect barFrame = CGRectMake(0, navigationBarBounds.size.height - progressBarHeight, navigationBarBounds.size.width, progressBarHeight);
    _progressView = [[NJKWebViewProgressView alloc] initWithFrame:barFrame];
    _progressView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin;
    [self loadUrl];
}

- (void)back {
    if ([self.name isEqualToString:@"周工作安排"] || [self.name isEqualToString:@"学校动态"]|| [self.name isEqualToString:@"内页返回"]) {
        self.webView = nil;
        [self.webView removeFromSuperview];
         [self.navigationController popViewControllerAnimated:NO];
    }else {
        [self.navigationController popViewControllerAnimated:NO];
    }
    
}

#pragma mark-控制器销毁
- (void)dealloc{
    self.webView = nil;
    [self.webView removeFromSuperview];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.navigationController.navigationBar addSubview:_progressView];
}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [_progressView removeFromSuperview];
}

-(void)loadUrl
{
    if ([self.type isEqualToString:@"LoadContent"]) {
        NSString * htmlcontent1 = [NSString stringWithFormat:@"<div id=\"webview_content_wrapper\"><head><style>img{width:%lfpx;height:%lfpx !important;margin-bottom:10px;}</style><style>video{width:%lfpx;height:%lfpx !important;margin-bottom:10px;}</style></head></div><div style='font-size:15px;'>%@</p></div>",Main_Screen_Width-20,Main_Screen_Width-140,Main_Screen_Width-20,Main_Screen_Width-140,self.content];
        
        NSString *jsString = [[NSString alloc] initWithFormat:@"document.body.style.fontSize=%f;",15.0];
        [self.webView stringByEvaluatingJavaScriptFromString:jsString];
        [self.webView loadHTMLString:htmlcontent1 baseURL:nil];
    }else{
        NSURLRequest *req = [[NSURLRequest alloc] initWithURL:_URL];
        [_webView loadRequest:req];
    }
}

- (void)webViewDidFinishLoad:(UIWebView *)webView{
    NSString *js = @"function imgAutoFit() { \
    var imgs = document.getElementsByTagName('img'); \
    for (var i = 0; i < imgs.length; ++i) {\
    var img = imgs[i];   \
    img.style.maxWidth = %f;   \
    } \
    }";
    js = [NSString stringWithFormat:js, [UIScreen mainScreen].bounds.size.width - 20];
    [webView stringByEvaluatingJavaScriptFromString:js];
    [webView stringByEvaluatingJavaScriptFromString:@"imgAutoFit()"];
    [ webView  stringByEvaluatingJavaScriptFromString:@"document.documentElement.style.webkitUserSelect='none';"];//静止用户选择
    [webView stringByEvaluatingJavaScriptFromString:@"document.documentElement.style.webkitTouchCallout=‘none‘;"];//静止长按
    [self addClickEventOnImg];//有的图片没有点击事件
    _imageArray= [self getImgs];//获取所有图片链接
    
}

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    if ([request.URL.scheme isEqualToString: @"img"])
    {
        NSString *url = [request.URL.absoluteString substringFromIndex:4];
        
        //启动图片浏览器， 跳转到图片浏览页面
        if (_imageArray.count != 0) {
            photos = [NSMutableArray arrayWithCapacity:10];
            for (NSInteger i = 0; i < _imageArray.count; i ++) {
                photo = [MWPhoto photoWithURL:[NSURL URLWithString:_imageArray[i]]];
                photo.caption = @"";
                [photos addObject:photo];
            }
            MWPhotoBrowser *browser = [[MWPhotoBrowser alloc] initWithDelegate:self];
            browser.displayActionButton = displayActionButton;//分享按钮,默认是
            browser.displayNavArrows = displayNavArrows;//左右分页切换,默认否
            browser.displaySelectionButtons = displaySelectionButtons;//是否显示选择按钮在图片上,默认否
            browser.alwaysShowControls = displaySelectionButtons;//控制条件控件 是否显示,默认否
            browser.zoomPhotosToFill = YES;//是否全屏,默认是
#if __IPHONE_OS_VERSION_MIN_REQUIRED < __IPHONE_7_0
            browser.wantsFullScreenLayout = YES;//是否全屏
#endif
            browser.enableGrid = enableGrid;//是否允许用网格查看所有图片,默认是
            browser.startOnGrid = startOnGrid;//是否第一张,默认否
            browser.enableSwipeToDismiss = YES;
            [browser showNextPhotoAnimated:YES];
            [browser showPreviousPhotoAnimated:YES];
            [browser setCurrentPhotoIndex:[_imageArray indexOfObject:url]];//当前点击的图片
            [self.navigationController pushViewController:browser animated:NO];
            
        }
        return NO;
    }
    //判断是否是单击
    if (navigationType == UIWebViewNavigationTypeLinkClicked)
    {
        NSURL *url = [request URL];
        if([[UIApplication sharedApplication] canOpenURL:url])
        {
            NSURLRequest *req = [[NSURLRequest alloc] initWithURL:url];
            [_webView setScalesPageToFit:YES];
            [_webView loadRequest:req];;
        }
        return NO;
    }
    return YES;
}


#pragma mark - MWPhotoBrowserDelegate

- (NSUInteger)numberOfPhotosInPhotoBrowser:(MWPhotoBrowser *)photoBrowser {
    return photos.count;
}

- (id )photoBrowser:(MWPhotoBrowser *)photoBrowser photoAtIndex:(NSUInteger)index {
    if (index < photos.count)
        return [photos objectAtIndex:index];
    return nil;
}

#pragma mark -- 获取文章中的图片个数
//  获取所有图片链接
- (NSMutableArray *)getImgs {
    NSMutableArray *arrImgURL = [[NSMutableArray alloc] init];
    int node = [self nodeCountOfTag:@"img"];
    for (int i = 0; i < node; i++) {
        NSString *jsString = [NSString stringWithFormat:@"document.getElementsByTagName('img')[%d].src", i];
        NSString *img = [self.webView stringByEvaluatingJavaScriptFromString:jsString];
        [arrImgURL addObject:img];
    }
    return arrImgURL;
}

///  获取某个标签的结点个数
- (int)nodeCountOfTag:(NSString *)tag {
    NSString *jsString = [NSString stringWithFormat:@"document.getElementsByTagName('%@').length", tag];
    int len = [[self.webView stringByEvaluatingJavaScriptFromString:jsString] intValue];
    return len;
}

///  为所有图片添加点击事件(网页中有些图片添加无效)
- (void)addClickEventOnImg {
    int node = [self nodeCountOfTag:@"img"];
    for (int i = 0; i < node; i++) {
        //利用重定向获取img.src，为区分，给url添加'img:'前缀
        NSString *jsString = [NSString stringWithFormat:
                              @"document.getElementsByTagName('img')[%d].onclick = \
                              function() { document.location.href = 'img:' + this.src; }",i];
        [self.webView stringByEvaluatingJavaScriptFromString:jsString];
    }
}

#pragma mark - NJKWebViewProgressDelegate
-(void)webViewProgress:(NJKWebViewProgress *)webViewProgress updateProgress:(float)progress
{
    [_progressView setProgress:progress animated:YES];
    if ([self.name isEqualToString:@"周工作安排"]) {
        self.title = @"周工作安排";
    }else {
        self.title = [_webView stringByEvaluatingJavaScriptFromString:@"document.title"];
    }
}

@end
